<template>
    <div class="activitytypeForm">
      <!-- element组件库的Dialog对话框默认可以通过点击 modal 关闭 Dialog，即点击空白处弹框可关闭。 -->
      <!-- :visible.sync 子组键改变父组件的值 控制子组件的显示-->
      <el-dialog title="新增用戶" :visible.sync="addDialogIsShow" :before-close="handleClose" :close-on-click-modal="false">
        <el-form   label-width="120px"  ref="addTeacherUploadForm" >
          <!-- 代码中的1表示第几个 和引入js的type变量对应 -->
          <el-form-item label="头像">
            <el-upload
              class="upload"
              :action="getUploadUrl"
              list-type="picture-card"
              :limit="1"
              accept="image/*"
              :on-change="(file,fileList)=>{imgHandleChange(file,fileList,1,this,'addActivitytypeUploadForm','activitytype')}"
              :on-remove="(file,fileList)=>{imgHandleRemove(1,this)}"
              :on-before="(file,fileList)=>{imghandleBeforeUpload(file,1,this)}"
              :auto-upload="false"
              :file-list="fileList[0]"
              ref="file1">
              <i class="el-icon-plus"></i>
            </el-upload>
            <!--<viewer-dialog ref="viewer" :images="imagesUp"></viewer-dialog>-->
          </el-form-item>
        </el-form>
        <el-form :model="activitytype" label-width="80px"  :rules="addActivitytypeRules" ref="addActivitytypeForm">
          <el-form-item label="姓名" prop="atname">
            <el-col :span="16">
              <el-input v-model="activitytype.atname" placeholder="请填入名称" clearable/>
            </el-col>
          </el-form-item>
          <el-form-item label="状态" prop="atstate">
            <el-col :span="16">
              <el-input v-model="activitytype.atstate" placeholder="请填入状态" clearable/>
            </el-col>
          </el-form-item>
          <el-form-item label="描述" prop="atdesc">
            <el-col :span="16">
              <el-input v-model="activitytype.atdesc" placeholder="请填入描述" clearable/>
            </el-col>
          </el-form-item>
      </el-form>
      <el-row>
         <el-col :span="12">
         <span>&nbsp;</span></el-col>
        <el-col :span="6">
           <span><el-button type="primary" @click="addActivitytype('addActivitytypeForm')">注册</el-button></span>
        </el-col>

    </el-row>
      </el-dialog>
    </div>
</template>

<script>
  import api from "../../../../axios/api"
  import rules from "../../../../static/js/validator/rules.js"
  import utils from "../../../../static/js/utils/upload.js"
    const favOptions = [];
    var initfavOption = [];
    export default {
        name: "addActivitytype",
        data(){
          return {activitytype:{},
              checkAll: false,

              favs: favOptions,
              isIndeterminate: true,
              addActivitytypeRules:{ name: [{required: true, message: "姓名不能为空", trigger: 'blur'}, {trigger: 'blur', validator: this.validateName},
                  {max: 20, min: 2, message: '长度异常 长度在2-20之间', trigger: 'blur'}, {
                    pattern: /^[\u0391-\uFFE5A-Za-z]+$/,
                    message: '姓名必须为中文',
                    trigger: 'blur'
                  }],
                cemail: [{required: true, message: "邮件不能为空", trigger: 'blur'}, {
                  trigger: 'change',
                  validator: rules.FormValidate.Form().validateEmail
                }],
                aid: [{required: true, message: "姓名不能为空", trigger: 'blur'}],
                apwd: [{required: true, message: "姓名不能为空", trigger: 'blur'}],
                cstate: [{required: true, message: "姓名不能为空", trigger: 'blur'}],
              },
              addDialogIsShow:false,
            //上传使用
            fileList: [[],[],[]], //缓存区文件
            uploadFile:[[],[],[]], //  上传用文件
            formData:{files:[]},
            imagesUp:null,
            //上传使用结束

          }
        },
      methods: {
         validateName:function(rule,value,callback){
           console.log(rule);
           if(value==1) {
              callback(new Error("1不正常"));
           }else{
             callback();
           }
  },
        init() {
          this.addDialogIsShow = true;
        },
        handleCheckAllChange(val) {
          this.activitytype.favs = val ? initfavOption : [];
          this.isIndeterminate = false;
        },
        handleCheckedFavsChange(value) {
          let checkedCount = value.length;
          this.checkAll = checkedCount === this.favs.length;
          this.isIndeterminate = checkedCount > 0 && checkedCount < this.favs.length;
        },
        //关闭页面
        handleClose() {
          this.addDialogIsShow = false;
          //给父组件传参
          this.$emit("addDialogIsShow", this.addDialogIsShow);
        },
        addActivitytype:function(addActivitytypeForm){
          this.$refs[addActivitytypeForm].validate(valid => {//此处refs对象和标签上的ref对应
            if (valid) {
              //如果通过验证 to do...
              console.log(this.activitytype);
              alert(this.activitytype.atname+"添加成功");
              this.setDataFromAxios();
              this.handleClose();
            } else {
              console.log('error submit!!')
              return false
            }
          });

        },
        handleUpSuccess(response, file, fileList) {
          if (response.code == 200) {
            this.ruleForm.cardUpImg = response.data[0];
            this.imagesUp = response.data;
            this.hideUp = fileList.length == 1;
            this.$message.success(response.msg);
          }
        },
        uploadImg:function(modelName,name){
          //  使用formdata格式
          let formData = new FormData();
          formData.append("model",modelName);//图片上传子目录
          console.log(formData);
          console.log(this.formData.files[name]);
          if (this.formData.files[name]) {
            formData.append("file", this.formData.files[name]);
          }
          console.log("----------------------------");
          console.log(formData);
          //为什么要封装一下方法 1.每个vue组件有自己的一些参数处理，简化调用本来这个setDataFromAxios这个方法属于api 重新封装就属于当前页面
          api.setDataFromAxios(this.$activitytype.state.host+"/uploadImg",formData,"post",{headers: { "Content-Type": "multipart/form-data" }})
            .then(dto=>{this.$message.info("头像上传成功");
              if(dto.code==200){
                this.activitytype.stimg = dto.obj;
              }
            });//.then方法 就是当服务器有返回的时候执行回调函数，对比jquery的ajax success:function（data）
        },
        setDataFromAxios:function(){
          //为什么要封装一下方法 1.每个vue组件有自己的一些参数处理，简化调用本来这个setDataFromAxios这个方法属于api 重新封装就属于当前页面
          api.setDataFromAxios("/api/activitytypeController/addActivitytype",this.activitytype,"post")
            .then(res=>{this.leagues = res.leagues});//.then方法 就是当服务器有返回的时候执行回调函数，对比jquery的ajax success:function（data）
        },
        updateView(e) {
          this.$forceUpdate();
        },
        imghandleBeforeUpload(file,type,vm) {

          return utils.UPLOAD.Upload().handleBeforeUpload(file,type,vm);
        },
        imgHandleChange(file, fileList, type,vm,modelName,name) {
          if(vm.fileList[type].length!=0){
            alert("请先删除再提交")
          }
          return utils.UPLOAD.Upload().handleChange(file, fileList, type,vm,modelName,name);
        },
        imgHandleRemove(type,vm) {

          return utils.UPLOAD.Upload().handleRemove( type,vm);
        },

      },
      computed:{
        getUploadUrl(){
          return      this.$activitytype.state.host+"/uploadImg";
        }
      },
      //监听
      watch: {
        addDialogIsShow(newValue, oldValue) {//配合:visible.sync监听变化
          this.addDialogIsShow = newValue;
        }
      },
      created() {
        for(var favindex=0;favindex < favOptions.length;favindex++){
          initfavOption.push(favOptions[favindex].name);
        }
      }
    }
</script>
<style scoped lang="stylus">
 .activitytypeForm
   margin 0 auto
   text-align left


</style>
